import React, {useEffect, useContext, useReducer} from 'react';
import axios from "axios";
import './css/film.css'

const initialState = {
    list: [],
    content: ""
}

const reducer = (preState, action) => {
    const newState = {...preState};
    if (action.type === "SET_LIST") {
        newState.list = action.value;
    } else if (action.type === "SET_CONTENT") {
        newState.content = action.value;
    }
    return newState;
}

const GlobalContext = React.createContext();
export default function App() {
    const [state, dispatch] = useReducer(reducer, initialState);

    useEffect(() => {
        axios.get("/test.json").then(res => {
            dispatch({
                type: "SET_LIST",
                value: res.data.data.films
            })
        })
    }, [])

    return <GlobalContext.Provider value={{
        state,
        dispatch
    }}>
        <div>
            {
                state.list.map(item =>
                    <Film key={item.filmId}
                          {...item}>
                    </Film>)
            }
            <FilmDetail></FilmDetail>
        </div>
    </GlobalContext.Provider>
}

function Film(props) {
    const {dispatch} = useContext(GlobalContext);

    return <div>
        <div className="film">
            <img onClick={() => dispatch({type: "SET_CONTENT", value: props.synopsis})}
                 src={props.poster}
                 alt={props.name}/>
            <span>{props.name}</span>
        </div>
    </div>
}

function FilmDetail() {
    const {state} = useContext(GlobalContext);

    return <div className="filmDetail">
        {state.content}
    </div>
}